<template>
	<div class="game-container report-container">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane
				:label="$t('agent.commission_contract')"
				name="1"
			></el-tab-pane>
			<el-tab-pane
				:label="$t('agent.rebate_contract')"
				name="2"
			></el-tab-pane>
			<el-form :inline="true" :model="queryData" label-width="auto">
				<el-form-item
					:label="$t('common.belong_merchant') + ':'"
					prop="merchantId"
				>
					<merchant-select
						v-model="queryData.merchantId"
						:placeholder="$t('common.all')"
						@change="selectMerchantHandle"
					></merchant-select>
				</el-form-item>
				<el-form-item :label="$t('agent.policy_type') + ':'">
					<el-select
						v-model="queryData.id"
						clearable
						:placeholder="$t('common.all')"
					>
						<el-option
							v-for="item in policyTypeArrid"
							:key="item.id"
							:label="item.policyType"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item style="margin-left: 8px">
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="activeName == 1 && hasPermission('204051')"
						icon="el-icon-folder"
						type="warning"
						:disabled="loading"
						size="medium"
						@click="create"
					>
						{{ $t('agent.add') }}
					</el-button>
					<el-button
						v-if="activeName == 2 && hasPermission('204055')"
						icon="el-icon-folder"
						type="warning"
						:disabled="loading"
						size="medium"
						@click="create"
					>
						{{ $t('agent.add') }}
					</el-button>
				</el-form-item>
			</el-form>
			<div class="content">
				<el-table
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					class="small-size-table"
					:data="policyTypeArr"
					:header-cell-style="getRowClass"
					highlight-current-row
				>
					<el-table-column
						prop="merchantId"
						align="center"
						:label="$t('common.belong_merchant')"
						min-width="230"
					>
						<template slot-scope="scope">
							<span>
								{{ merchantFilter(scope.row.merchantId) }}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="policyType"
						align="center"
						:label="$t('agent.policy_type')"
						min-width="230"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.policyType || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="policyDec"
						align="center"
						:label="$t('agent.policy_desc')"
						min-width="230"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.policyDec || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="createdBy"
						align="center"
						:label="$t('common.createBy')"
						min-width="230"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.createdBy || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="createdAt"
						align="center"
						:label="$t('common.createAt')"
						min-width="230"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.createdAt || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="updatedBy"
						align="center"
						:label="$t('agent.last_modified_people')"
						min-width="230"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.updatedBy || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="updatedAt"
						align="center"
						:label="$t('agent.last_modified_time')"
						min-width="230"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.updatedAt || '-' }}</span>
						</template>
					</el-table-column>

					<el-table-column
						align="center"
						:label="$t('common.actions')"
						width="285"
						fixed="right"
					>
						<template slot-scope="scope">
							<el-button
								v-if="
									activeName == 1 && hasPermission('204054')
								"
								type="primary"
								icon="el-icon-edit"
								:disabled="scope.row.status === 1"
								size="medium"
								@click="openEdit(scope.row)"
							>
								{{ $t('common.edit') }}
							</el-button>
							<el-button
								v-if="
									activeName == 2 && hasPermission('204057')
								"
								type="primary"
								icon="el-icon-edit"
								:disabled="scope.row.status === 1"
								size="medium"
								@click="openEdit(scope.row)"
							>
								{{ $t('common.edit') }}
							</el-button>
							<el-button
								v-if="
									activeName == 1 && hasPermission('204052')
								"
								type="danger"
								icon="el-icon-delete"
								size="medium"
								:disabled="scope.row.status === 1"
								@click="deleteBtn(scope.row)"
							>
								{{ $t('common.delete') }}
							</el-button>
							<el-button
								v-if="
									activeName == 2 && hasPermission('204056')
								"
								type="danger"
								icon="el-icon-delete"
								size="medium"
								:disabled="scope.row.status === 1"
								@click="deleteBtn(scope.row)"
							>
								{{ $t('common.delete') }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-tabs>
		<!-- 佣金 -->
		<el-dialog
			:title="title"
			:visible.sync="edit"
			:destroy-on-close="true"
			:width="getWidth('1290px', 1.35)"
			class="rempadding"
		>
			<el-form
				ref="form"
				:rules="rules"
				label-width="auto"
				:model="ruleForm"
			>
				<el-form-item
					:label="$t('common.choose_merchant') + ':'"
					prop="merchantId"
				>
					<merchant-select
						v-model="ruleForm.merchantId"
						:placeholder="$t('common.please_choose')"
						:disabled="
							Boolean(ruleForm.id) || merchantList.length === 1
						"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="$t('agent.policy_type') + ':'"
					prop="policyType"
				>
					<el-input
						v-model="ruleForm.policyType"
						clearable
						:maxlength="10"
						size="medium"
						style="width: 260px"
						:placeholder="$t('agent.rule_input_tip2-10')"
						:disabled="loading"
						@keyup.enter.native="enterSearch"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="$t('agent.policy_desc') + ':'"
					prop="policyDec"
				>
					<el-input
						v-model="ruleForm.policyDec"
						clearable
						:maxlength="30"
						size="medium"
						style="width: 260px"
						:placeholder="$t('common.please_enter')"
						:disabled="loading"
						@keyup.enter.native="enterSearch"
					></el-input>
				</el-form-item>
				<FormTable
					ref="tableForm"
					:settings-data="dataList"
					:edit-contract-list="dataList"
					:top-form="ruleForm"
					rebate-rate-field-name="rebateRatio"
					:contract-type="activeName * 1"
					:column-config="columnConfig"
					:custom-form="true"
				></FormTable>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="edit = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="subAddOrEidt">
					{{ $t('common.sure') }}
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import list from '@/mixins/list'
import FormTable from '@/components/FormTable'
import columnConfig from './columnConfig.js'
import templateData from './templateData.js'
import { Decimal } from 'decimal.js'

export default {
	name: 'ContractMinConfig',
	components: {
		FormTable
	},
	mixins: [list],
	data() {
		this.loadData = this.throttle(this.loadData, 1000)
		return {
			policyTypeConfigId: '',
			policyTypeArrid: [],
			policyTypeArr: [],
			policyType: '',
			policyDec: '',
			labelName: '',
			dataList: [],
			activeName: '1',
			edit: false,
			ruleForm: {
				policyType: '',
				policyDec: ''
			},
			editrebate: false,
			queryData: {
				merchantId: '',
				id: ''
			},
			contractType: 1,

			isDisabled: true,
			title: '',
			popupgGameLosscheck: '',
			columnConfig: columnConfig,
			templateData: templateData,
			rules: {
				merchantId: [
					{
						required: true,
						message: this.$t('agent.rule_select_tip_merchant'),
						trigger: 'blur'
					}
				],
				policyType: [
					{
						required: true,
						message: this.$t('agent.policy_type_null'),
						trigger: 'blur'
					},
					{
						max: 10,
						min: 2,
						message: this.$t('agent.rule_length_tip2-10'),
						trigger: 'blur'
					}
				],
				policyDec: [
					{
						required: true,
						message: this.$t('agent.policy_desc_null'),
						trigger: 'blur'
					},
					{
						max: 30,
						min: 2,
						message: this.$t('agent.rule_length_tip2-30'),
						trigger: 'blur'
					}
				]
			}
		}
	},
	computed: {
		merchantList() {
			return this.$store.getters.merchantList || []
		}
	},
	created() {},
	mounted() {},
	methods: {
		selectMerchantHandle(merchantId) {
			this.getpolicyTypeArr(merchantId)
			this.queryData.id = ''
		},
		create() {
			this.pageType = 'e'
			this.title = this.$t('common.create')
			this.edit = true
			this.ruleForm = {
				policyType: '',
				policyDec: '',
				merchantId: ''
			}
			if (this.merchantList.length === 1) {
				this.ruleForm.merchantId = this.merchantList[0]['id']
			}
		},
		reset() {
			this.queryData.merchantId = ''
			this.queryData.id = ''
			this.pageNum = 1
			this.loadData()
		},
		openEdit(val, index) {
			this.edit = true
			this.title = this.$t('common.edit')
			this.ruleForm = { ...val }
			// this.$nextTick(() => {
			// 	this.$refs['tableForm'].getRebateRatioList()
			// })

			const params = {
				contractType: this.contractType,
				policyTypeConfigId: this.ruleForm.id,
				merchantId: this.ruleForm.merchantId
			}
			this.$api.queryRebateRatioAPI(params).then((res) => {
				this.dataList = res.data.contractConfigs || []
				this.dataList.forEach((item) => {
					item.rebateRatio = this._decimalToMul(item.rebateRatio)
				})
				this.$refs['tableForm'].getRebateRatioList()
			})
		},

		openDetail(rowData) {
			this.rowData = Object.assign({}, rowData)
			this.rowData.zhengce = '1'
			this.edit = true
			this.title = this.$t('common.edit')
		},
		loadData() {
			this.getpolicyTypeArr()
			const contractType = this.activeName
			this.$api
				.getProxyMinContractPolicyTypeList({
					contractType,
					...this.queryData
				})
				.then((res) => {
					const { code } = res
					if (res && code && code === 200) {
						this.policyTypeArr = res.data || {}
					} else {
						this.policyTypeArr = []
					}
				})
		},
		getpolicyTypeArr(merchantId = '') {
			this.$api
				.getProxyMinContractPolicyTypeList({
					contractType: this.activeName,
					merchantId: merchantId || this.queryData.merchantId
				})
				.then((res) => {
					const { code } = res
					if (res && code && code === 200) {
						this.policyTypeArrid = res.data || {}
					} else {
						this.policyTypeArrid = []
					}
				})
		},
		// 提交表单
		subAddOrEidt() {
			let form1 = false
			this.$refs['form'].validate((valid) => {
				if (valid) {
					form1 = true
				} else {
					form1 = false
				}
			})
			if (form1) {
				const refForm = this.$refs.tableForm
				refForm.$refs.tableForm.validate((valid) => {
					if (valid) {
						const minContactList = JSON.parse(
							JSON.stringify(refForm.tableForm)
						)
						if (!minContactList.length) {
							return this.$confirm(
								this.$t('agent.rule_contract_tip2'),
								this.$t('agent.tip'),
								{
									confirmButtonText: this.$t(
										'common.confirm'
									),
									showCancelButton: false,
									type: 'warning'
								}
							)
						}
						minContactList.forEach((item) => {
							item.rebateRatio = this._decimalToDiv(
								item.rebateRatio
							)
						})
						const data = {
							contractType: this.activeName * 1,
							id: this.ruleForm.id,
							policyType: this.ruleForm.policyType,
							policyDec: this.ruleForm.policyDec,
							merchantId: this.ruleForm.merchantId,
							minContactList
						}

						if (this.title === this.$t('common.create')) {
							this.setproxyMinContractaddPolicyType(data)
						} else if (this.title === this.$t('common.edit')) {
							this.setBannerUpdate(data)
						}
					}
				})
			}
		},
		_decimalToMul(val) {
			return val * 1 === 0 ? 0 : new Decimal(val).mul(100).toNumber()
		},
		_decimalToDiv(val, y) {
			return val * 1 === 0 ? 0 : new Decimal(val).div(y || 100).toNumber()
		},
		setproxyMinContractaddPolicyType(val) {
			this.$api
				.getproxyMinContractaddPolicyType(val)
				.then((res) => {
					if (res?.code === 200) {
						this.$message.success(this.$t('agent.create_success'))
						this.loadData()
					}
					this.edit = false
					this.editrebate = false
				})
				.catch(() => {})
		},
		setBannerUpdate(val) {
			this.$api.getproxyMinContractupdatePolicyType(val).then((res) => {
				if (res?.code === 200) {
					this.$message({
						message: this.$t('common.edit_success'),
						type: 'success'
					})
					this.edit = false
					this.editrebate = false
					this.loadData()
				}
			})
		},
		deleteBtn(val) {
			this.$confirm(
				`<strong>${this.$t(
					'agent.is_delete_enter'
				)}</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
					'common.del_tips'
				)}</span>`,
				this.$t('agent.tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.$api
						.getproxyMinContractdeletePolicyType({ id: val.id })
						.then((res) => {
							if (res?.code === 200) {
								this.$message.success(
									this.$t('agent.delete_success')
								)
								this.loadData()
							}
						})
				})
				.catch(() => {})
		},

		handleClick(tab) {
			const name = tab.name
			if (name === '1') {
				this.contractType = 1
			} else if (name === '2') {
				this.contractType = 2
			}
			this.queryData.merchantId = ''
			this.queryData.id = ''
			this.loadData()
		}
		//

		// reset() {
		// 	this.pageNum = 1
		// 	this.formTime.time = [start, end]
		// 	this.loadData()
		// }
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}

.view-container {
	min-height: 500px;
}

::v-deep .game-container .content {
	margin-top: 0px !important;
}

.game-container >>> .el-form-item__error {
	padding-left: 24px;
}

.headstyle {
	display: flex;
	justify-content: space-between;
	width: 70%;
	margin: 30px auto 5px;

	p {
		color: #87898d;
		font-weight: 700;
		line-height: 24px;
	}
}

.hr {
	margin-left: 262px;
}

.fr {
	margin-left: 938px;
	margin-top: 30px;
}

::v-deep input::-webkit-inner-spin-button {
	-webkit-appearance: none !important;
}

::v-deep .el-input-number__decrease,
::v-deep .el-input-number__increase {
	display: none;
}
</style>
